const { ipcMain, Notification } = require('electron')
const { SerialPort } = require('serialport')

var receive_event
var strCard
ipcMain.on('card_init', (event, val) => {
    // 定义串口信息
    const port = new SerialPort({
        path: val,
        baudRate: 115200
    },res => {
        if (res != null) {
            new Notification({
                title: 'TIMS NOTICE',
                body: '串口打开失败！'
            }).show()
        }
    })

    port.open(res => {
        try {
            if (res) {
                if (res.message != 'Port is opening') {
                    return console.log('Error opening port: ', res.message)
                }
            }
            send('AA BB 00 06 00 00 FF 00 00 05 47')
        } catch (error) {
            console.log(error)
        }
    })

    port.on('error', err => {
        e.sender.send('card_error', err)
    })

    port.on('data',data => {
        var card = data.toString('hex')
        if (card.indexOf('aa') == 0) {
            strCard = card   
        } else {
            strCard += card
        }
        
        if (strCard.length == 34) {
            // console.log(data.toString('hex'))
            send('AA BB 00 06 00 00 FF 00 00 05 47')
            return receive_event.reply('card_find_return', strCard)
        }else if (strCard == 'aabb00050000ff000041') {
            event.reply('card_status', true)
        }
    })

    // 读取ic卡
    ipcMain.on('card_find', (e, val) => {
        receive_event = e
        send('AA BB 00 0C 00 00 10 00 00 00 04 08 FB A9 50 5B F2')
    })


    function send(val) {
        //将一个十六进制报文转为字符数组
        strs = val.split(" ");
        for(let i = 0;i<strs.length;i++){
            strs[i] = "0x"+strs[i];
        }//每个字符加上0x
        //将数组放到buffer
        let buffer = Buffer.from(strs);
        port.write(buffer)
        port.drain(err => {
            if (err) {
                return
            }
        })
    }

})


// port.open(res => {
//     try {
//         if (res) {
//             if (res.message != 'Port is opening') {
//                 return console.log('Error opening port: ', res.message)
//             }
//         }
//         // 获取所有打开的BrowserWindow
//         const allWindows = BrowserWindow.getAllWindows();
//         console.log(allWindows)

//     } catch (error) {

//     }
// })

// AA BB 00 05 00 00 FF 00 00 41



const func = {
  // 发送数据

}



module.exports = func;
